package org.example.ideavr.service.impl;

import org.example.ideavr.annotation.AutoFill;
import org.example.ideavr.common.BaseException;
import org.example.ideavr.mapper.UserMapper;
import org.example.ideavr.pojo.dto.UserDTO;
import org.example.ideavr.pojo.dto.UserLoginDTO;
import org.example.ideavr.pojo.dto.UserRegisterDTO;
import org.example.ideavr.pojo.entity.User;
import org.example.ideavr.pojo.vo.UserVO;
import org.example.ideavr.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    /**
     * 用户登录
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        // 查询数据
        User user = userMapper.selectByUsername(username);

        // 处理sql异常
        if(user == null){
            throw new BaseException("用户不存在");
        }
        // 密码比对

        if(!user.getPassword().equals(password)){
            throw new BaseException("密码错误");
        }
        // 返回实体
        return user;
    }

    /**
     * 用户注册
     */
    @Override
    public void register(UserRegisterDTO userRegisterDTO) {
        String password = userRegisterDTO.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        User user = new User();
        BeanUtils.copyProperties(userRegisterDTO, user);
        user.setPassword(password);

        userMapper.insert(user);
    }

    /**
     * 用户信息查询
     */

    @Override
    public UserVO getUserById(Long id) {
        return userMapper.selectById(id);
    }

    /**
     * 用户信息更新
     */
    @Override
    public void updateUser(UserDTO userDTO) {

        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        user.setUpdateTime(LocalDateTime.now());

        userMapper.userUpdate(user);
    }
}
